package com.lcz.mytest.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentProvider;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lcz.mytest.R;
import com.lcz.mytest.activity.MainActivity;
import com.lcz.mytest.activity.PastStockChartActivity;
import com.lcz.mytest.activity.PresentStockChartActivity;
import com.lcz.mytest.adapter.CollectAdapter;
import com.lcz.mytest.adapter.StockListAdapter;
import com.lcz.mytest.db.StockAPI;
import com.lcz.mytest.db.UserService;
import com.lcz.mytest.domain.StockList;
import com.lcz.mytest.domain.User;
import com.lcz.mytest.utils.ViewUtils;
import com.lcz.mytest.widget.CustomProgressDialog;

import net.tsz.afinal.http.AjaxCallBack;

import java.util.ArrayList;
import java.util.List;

import static com.lcz.mytest.activity.MainActivity.USERNAME;

//收藏个股Fragment
public class CollectFragment extends Fragment {
    private FrameLayout frameLayout;
    private View view_collect;//收藏页面
    private PullToRefreshListView collect_list;
    private List<User> codeList = new ArrayList<>();
    private CustomProgressDialog loading_dialog;//加载动画
    private CollectAdapter adapter;

    MyReceiver receiver;
    public static final String RECEIVER_INFILTER = "com.lll";
    private TextView collect_tip;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (frameLayout == null) { // 之前的frameLayout 已经记录了一个爹了 爹是之前的ViewPager
            frameLayout = new FrameLayout(getActivity());
            view_collect = inflater.inflate(R.layout.activity_collect, null);
            init(); // 在FrameLayout中 添加不同的界面
        } else {
            ViewUtils.removeParent(frameLayout);// 移除frameLayout之前的爹
        }

        return frameLayout; // 拿到当前viewPager 添加这个framelayout
    }

    private void init() {
        if (view_collect != null) {
            collect_list = (PullToRefreshListView) view_collect.findViewById(R.id.collect_list);
            collect_tip = (TextView) view_collect.findViewById(R.id.collect_tip);
            collect_list.setMode(PullToRefreshBase.Mode.BOTH);
            if (MainActivity.isLogin) {//用户已登录
                //获取收藏列表
                UserService service = new UserService(getActivity());
                final List<User> codeList = service.collectList(MainActivity.USERNAME);
                if (codeList == null) {
                    collect_tip.setVisibility(View.VISIBLE);
                    collect_list.setVisibility(View.GONE);
                } else {
                    collect_tip.setVisibility(View.GONE);
                    collect_list.setVisibility(View.VISIBLE);
                    upData(codeList);
                }
                //上下拉刷新
                collect_list.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
                    @Override
                    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                        if (codeList == null) {
                            collect_tip.setVisibility(View.VISIBLE);
                        } else {
                            collect_tip.setVisibility(View.GONE);
                            upData(codeList);
                            collect_list.onRefreshComplete();//刷新结束
                        }
                    }

                    @Override
                    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

                    }
                });

            } else {
                collect_tip.setText("你暂未登录，请先登录后查看收藏记录~");
            }
        }


        collect_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                String type = codeList.get(position - 1).getDataType();
                if (type.equals("历史数据")) {
                    Intent intent = new Intent(getActivity(), PastStockChartActivity.class);
                    intent.putExtra("symbol", codeList.get(position - 1).getStockCode());
                    getActivity().startActivity(intent);
                } else if (type.equals("实时数据")) {
                    Intent intent = new Intent(getActivity(), PresentStockChartActivity.class);
                    intent.putExtra("symbol", codeList.get(position - 1).getStockCode());
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    getActivity().startActivity(intent);
                }
            }
        });
        //将收藏页面添加到首页
        frameLayout.addView(view_collect, new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
        view_collect.setVisibility(View.VISIBLE);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        //注册广播
        receiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(RECEIVER_INFILTER);
        activity.registerReceiver(receiver, filter);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(receiver);
    }

    //页面更新处理
    private void upData(List<User> list) {
        codeList.clear();//下拉刷新时清空
        codeList.addAll(list);
        if (adapter == null) {
            adapter = new CollectAdapter(codeList, getActivity());
            collect_list.setAdapter(adapter);
        } else {
            adapter.upDataList(codeList);
            adapter.notifyDataSetChanged();
        }
    }

    private class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean login = intent.getBooleanExtra("login", false);
            if (login) {
                //登录状态

                //获取收藏列表
                UserService service = new UserService(getActivity());
                final List<User> codeList = service.collectList(MainActivity.USERNAME);
                if (codeList == null) {
                    collect_tip.setText("暂未有收藏记录~");
                    collect_tip.setVisibility(View.VISIBLE);
                } else {
                    collect_tip.setVisibility(View.GONE);
                    collect_list.setVisibility(View.VISIBLE);
                    upData(codeList);
                }
            } else {
                //退出登录状态
                collect_tip.setText("你暂未登录，请先登录后查看收藏记录~");
                collect_tip.setVisibility(View.VISIBLE);
                collect_list.setVisibility(View.GONE);

            }
        }
    }


}
